package com.ccp.dev.im.server.proxy.impl;

import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.im.model.ImFriendMessage;
import com.ccp.dev.im.model.ImRoomMessage;
import com.ccp.dev.im.model.ImUser;
import com.ccp.dev.im.server.constant.Constants;
import com.ccp.dev.im.server.model.MessageWrapper;
import com.ccp.dev.im.server.model.proto.MessageBodyProto;
import com.ccp.dev.im.server.model.proto.MessageProto;
import com.ccp.dev.im.server.proxy.MessageProxy;
import com.ccp.dev.im.service.ImFriendMessageService;
import com.ccp.dev.im.service.ImRoomMessageService;
import com.ccp.dev.im.service.ImUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

@Component
public class MessageProxyImpl implements MessageProxy {
	private final static Logger log = LoggerFactory.getLogger(MessageProxyImpl.class);
	
	@Resource
	private ImFriendMessageService imFriendMessageService;
	@Resource
	private ImRoomMessageService imRoomMessageService;
	@Resource
	private ImUserService imUserService;

    @Override
    public MessageWrapper convertToMessageWrapper(String sessionId , MessageProto.Model message) {
    	
        
        switch (message.getCmd()) {
			case Constants.CmdType.BIND:
				 try {
		            	return new MessageWrapper(MessageWrapper.MessageProtocol.CONNECT, message.getSender(), null,message);
		            } catch (Exception e) {
		                e.printStackTrace();
		            }
				break;
			case Constants.CmdType.HEARTBEAT:
				try {
	                 return new MessageWrapper(MessageWrapper.MessageProtocol.HEART_BEAT, sessionId,null, null);
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
				break;
			case Constants.CmdType.ONLINE:
				try {
					return new MessageWrapper(MessageWrapper.MessageProtocol.ON_LINE, sessionId,null, null);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case Constants.CmdType.OFFLINE:
				try {
					return new MessageWrapper(MessageWrapper.MessageProtocol.OFF_LINE, sessionId,null, null);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case Constants.CmdType.MESSAGE:
					try {
						  ImUser imUser = imUserService.getOneById(sessionId);
						  MessageProto.Model.Builder  result = MessageProto.Model.newBuilder(message);
						  result.setTimeStamp(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
						  //存入发送人sessionId
						  result.setSender(sessionId);
						  //临时占用两个字段 用于存储用户名 ， 和头像
						  result.setSign(imUser.getUsername());
						  result.setToken(imUser.getAvatar());
						  message =  MessageProto.Model.parseFrom(result.build().toByteArray());
						  //判断消息是否有接收人
						  if(StringUtils.isNotEmpty(message.getReceiver())){
							  return new MessageWrapper(MessageWrapper.MessageProtocol.REPLY, sessionId,message.getReceiver(), message);
						  }else if(StringUtils.isNotEmpty(message.getGroupId())){
							  return new MessageWrapper(MessageWrapper.MessageProtocol.GROUP, sessionId, null,message);
						  }else {
							  return new MessageWrapper(MessageWrapper.MessageProtocol.SEND, sessionId, null,message);
						  }
		            } catch (Exception e) {
		                e.printStackTrace();
		            }
					break;
			default:
		} 
        return null;
    }

    @Override
	public String saveMessageToDB(MessageWrapper message) {
    	try{
			Object obj = convertMessageWrapperToBean(message);
			if(obj!=null){
				if(obj instanceof ImFriendMessage){
					ImFriendMessage imFriendMessage = (ImFriendMessage)obj ;
					imFriendMessageService.add(imFriendMessage);
					return imFriendMessage.getId();
				}else if(obj instanceof ImRoomMessage){
					ImRoomMessage imRoomMessage = (ImRoomMessage)obj ;
					imRoomMessageService.add(imRoomMessage);
					return imRoomMessage.getId();
				}
			}
			return null;
    	}catch(Exception e){
    		 log.error("MessageProxyImpl  user "+message.getSessionId()+" send msg to "+message.getReSessionId()+" error");
    		 throw new RuntimeException(e.getCause());
    	} 
	}

	@Override
	public void updateOnlineStatusToDB(String sessionId , String status) {
		try{
			ImUser imUser = new ImUser();
			imUser.setId(sessionId);
			imUser.setStatus(status);
			imUserService.update(imUser);
		}catch(Exception e){
			throw new RuntimeException(e.getCause());
		}
	}


	private Object convertMessageWrapperToBean(MessageWrapper message){
    	try{
    		//保存非机器人消息
    		if(!message.getSessionId().equals(Constants.ImserverConfig.REBOT_SESSIONID)){
    			MessageProto.Model  msg =  (MessageProto.Model)message.getBody();
            	MessageBodyProto.MessageBody  msgConten =  MessageBodyProto.MessageBody.parseFrom(msg.getContent());
				String groupId = msg.getGroupId();
				String context = msgConten.getContent();
				Integer msgType = getMsgType(msgConten.getContent());
				String fileName = getFileName(msgType,context);
				if(StringUtils.isEmpty(groupId)){
					//單聊
					ImFriendMessage imFriendMessage = new ImFriendMessage();
					imFriendMessage.setId(UUIDUtils.getUUIDFor32());
					imFriendMessage.setFromId(message.getSessionId());
					imFriendMessage.setToId(message.getReSessionId());
					imFriendMessage.setContent(context);
					imFriendMessage.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(msg.getTimeStamp()));
					imFriendMessage.setMsgType(msgType);
					imFriendMessage.setIsBack(Constants.MsgStatus.IS_BACK_N);
					imFriendMessage.setIsDel(Constants.MsgStatus.IS_Del_N);
					imFriendMessage.setFileName(fileName);
					imFriendMessage.setIsRead(message.getSessionId().equals(message.getReSessionId())?Constants.MsgStatus.IS_READ_Y:Constants.MsgStatus.IS_READ_N);
					return imFriendMessage;
				}else{
					//群聊
					ImRoomMessage imRoomMessage = new ImRoomMessage();
					imRoomMessage.setId(UUIDUtils.getUUIDFor32());
					imRoomMessage.setFromId(message.getSessionId());
					imRoomMessage.setToRoom(groupId);
					imRoomMessage.setContent(context);
					imRoomMessage.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(msg.getTimeStamp()));
					imRoomMessage.setMsgType(msgType);
					imRoomMessage.setIsBack(Constants.MsgStatus.IS_BACK_N);
					imRoomMessage.setIsDel(Constants.MsgStatus.IS_Del_N);
					imRoomMessage.setFileName(fileName);
					return imRoomMessage;
				}
    		}
    	}catch(Exception e){
    		 throw new RuntimeException(e.getCause());
    	} 
    	return null;
    }

	/**
	 * 获取消息类型
	 * @param content  消息内容
	 * @return 类型
	 */
	private Integer getMsgType(String content){
		String picturePattern = "^img\\[\\/system\\/attachFile\\/download\\?fileId\\=[\\s\\S]+\\]\\[[\\s\\S]+\\]$";
		String filePattern = "^file\\(\\/system\\/attachFile\\/download\\?fileId\\=[\\s\\S]+\\)\\[[\\s\\S]+\\]$";
		String audioPattern = "^audio\\[[\\s\\S]+\\]$";
		String videoPattern = "^video\\[[\\s\\S]+\\]$";
    	if(StringUtils.isNotEmpty(content)){
    		if(Pattern.matches(picturePattern, content)){
    			return Constants.MsgType.PICTURE;
			}else if(Pattern.matches(filePattern, content)){
				return Constants.MsgType.FILE;
			}else if(Pattern.matches(audioPattern, content)){
                return Constants.MsgType.AUDIO;
            }else if(Pattern.matches(videoPattern, content)){
                return Constants.MsgType.VIDEO;
            }else{
				return Constants.MsgType.TEXT;
			}
		}
		return Constants.MsgType.TEXT;
	}
	/**
	 * 获取文件名称
	 * @param type  消息类型
	 * @param content  消息内容
	 * @return 类型
	 */
	private String getFileName(Integer type,String content){
    	if(StringUtils.isNotEmpty(content)){
    		if(Constants.MsgType.PICTURE.equals(type)){
    			return content.replaceAll("^img\\[\\/system\\/attachFile\\/download\\?fileId\\=[\\s\\S]+\\]\\[|\\]$","");
			}else if(Constants.MsgType.FILE.equals(type)){
				return content.replaceAll("^file\\(\\/system\\/attachFile\\/download\\?fileId\\=[\\s\\S]+\\)\\[|\\]$","");
			}else if(Constants.MsgType.AUDIO.equals(type)){
				return "";
            }else if(Constants.MsgType.VIDEO.equals(type)){
				return "";
            }
		}
		return "";
	}

	@Override
	public MessageProto.Model getOnLineStateMsg(String sessionId) {
		MessageProto.Model.Builder  result = MessageProto.Model.newBuilder();
		result.setTimeStamp(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		result.setSender(sessionId);//存入发送人sessionId
		result.setCmd(Constants.CmdType.ONLINE);
		return result.build();
	}



	@Override
	public MessageProto.Model getOffLineStateMsg(String sessionId) {
		MessageProto.Model.Builder  result = MessageProto.Model.newBuilder();
		result.setTimeStamp(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		result.setSender(sessionId);//存入发送人sessionId
		result.setCmd(Constants.CmdType.OFFLINE);
		return result.build();
	}



	@Override
	public MessageWrapper getReConnectionStateMsg(String sessionId) {
		 MessageProto.Model.Builder  result = MessageProto.Model.newBuilder();
		 result.setTimeStamp(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		 result.setSender(sessionId);//存入发送人sessionId
		 result.setCmd(Constants.CmdType.RECON);
		 return  new MessageWrapper(MessageWrapper.MessageProtocol.SEND, sessionId, null,result.build());
	}

    
}
